﻿using Microsoft.VisualStudio.Shell;
using Sasa.QualityTools.CodeAnalysis.Common;
using System;
using System.Text;
using System.Threading;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator
{
    internal class ActivityLogger : ILogger
    {
        private const string ExtensionName = "FxCop Integrator";


        void ILogger.Info(string message, params object[] args)
        {
            var culture = Thread.CurrentThread.CurrentUICulture;
            ActivityLog.LogInformation(ExtensionName, String.Format(culture, message, args));
        }

        void ILogger.Warn(string message, params object[] args)
        {
            var culture = Thread.CurrentThread.CurrentUICulture;
            ActivityLog.LogWarning(ExtensionName, String.Format(culture, message, args));
        }

        void ILogger.Error(string message, params object[] args)
        {
            var culture = Thread.CurrentThread.CurrentUICulture;
            ActivityLog.LogError(ExtensionName, String.Format(culture, message, args));
        }

        void ILogger.Error(Exception exception, string message,  params object[] args)
        {
            var text = new StringBuilder();
            var culture = Thread.CurrentThread.CurrentUICulture;
            text.AppendLine(String.Format(culture, message, args));
            text.AppendLine(FormatException(exception, "    "));
            ActivityLog.LogError(ExtensionName, text.ToString());
        }

        private static string FormatException(Exception e, string indent)
        {
            var text = new StringBuilder();
            text.AppendLine(indent + "Type: " + e.GetType().FullName);
            text.AppendLine(indent + "Message: " + e.Message);
            text.AppendLine(indent + "Source: " + e.Source);
            text.AppendLine(indent + "Help Link: " + e.HelpLink);
            text.AppendLine(indent + "Stack Trace: " + e.StackTrace);
            if (e.InnerException != null)
            {
                text.AppendLine(FormatException(e.InnerException, indent + "    "));
            }
            return text.ToString();
        }
    }
}
